<template>
    <div>
        <van-address-edit
            ref="addressEdit"
            :area-list="areaList"
            show-postal
            show-delete
            show-set-default
            show-search-result
            :search-result="searchResult"
            :area-columns-placeholder="['请选择', '请选择', '请选择']"
            :address-info="detail"
            @save="onSave"
            @delete="onDelete"
            @change-detail="onChangeDetail"
        />
    </div>
</template>

<script>
import { Toast } from 'vant';

export default {
    data() {
        return {
            areaList: {
                province_list: {
                    110000: '北京市',
                    120000: '天津市',
                },
                city_list: {
                    110100: '北京市',
                    120100: '天津市',
                },
                county_list: {
                    110101: '东城区',
                    110102: '西城区',
                    // ....
                },
            },
            searchResult: [],
        };
    },
    computed: {
        // 根据我动态路由里的id 去拿地址列表里对应的地址
        detail() {
            // 什么是计算属性
            // 当依赖值发生改变时重新计算结果
            // this.$route.params.id
            return this.$store.state.address.addressList.find(item => item.id == this.$route.params.id)
        }
    },
    created() {
        console.log(this.detail)
        // setAddressDetail(this.detail)

    },
    mounted() {
        // console.log(this.$refs.addressEdit.setAddressDetail('123'))
    },
    methods: {
        onSave(content) {
            // 可能是编辑
            // 也可能是新增
            if (this.$route.params.id) {
                this.$api.editAddress({ ...content, id: this.$route.params.id }).then(res => {
                    if (res.success) {
                        Toast('修改成功');
                        this.$router.push('/address')
                    }
                })
            } else {
                this.$api.addAddress(content).then(res => {
                    if (res.success) {
                        Toast('添加成功');
                        this.$router.push('/address')
                    }
                })
            }
        },
        onDelete() {
            Toast('delete');
        },
        onChangeDetail(val) {
            if (val) {
                this.searchResult = [
                    {
                        name: '黄龙万科中心',
                        address: '杭州市西湖区',
                    },
                ];
            } else {
                this.searchResult = [];
            }
        },
    },
};
</script>

<style>
</style>